import { nextTick, ref } from 'vue'
import { ElInput } from 'element-plus'
import { useTagsStore } from '@/stores/tagSelectorStore'
import { storeToRefs } from 'pinia'
export default function () {
  const { tagsVisible, dynamicTags } = storeToRefs(useTagsStore())
  const inputValue = ref('')
  const inputVisible = ref(false)
  const InputRef = ref<InstanceType<typeof ElInput>>()

  const handleClose = (tag: string) => {
    if (dynamicTags.value.length === 1) {
      tagsVisible.value = false
    }
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  }

  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value!.input!.focus()
    })
  }

  const handleInputConfirm = () => {
    if (inputValue.value) {
      dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
  }
  const tagsPush = (key: string) => {
    if (tagsVisible.value === false) {
      tagsVisible.value = true
    }
    const bool = dynamicTags.value.find((item) => item === key)
    if (!bool) {
      dynamicTags.value.push(key)
    }
  }

  return {
    tagsVisible,
    dynamicTags,
    inputValue,
    InputRef,
    inputVisible,
    handleClose,
    showInput,
    handleInputConfirm,
    tagsPush
  }
}
